<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-12-27 10:03:28
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-03-23 09:42:37
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\VaccineInject\components\Edit.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
 * 疫苗注射记录-修改
-->
<script setup lang="ts">
import { reactive, ref, unref } from 'vue'

import { ContentWrap } from '@/components/ContentWrap'
import { Form } from '@/components/Form'
import { spDrugListApi } from '@/api/sp/drug'

// import { UploadMultiple } from '@/components/UploadMultiple'

import { useForm } from '@/hooks/web/useForm'

import { required } from '@/utils/formRules'
import { Table } from '@/components/Table'

// import { adminFaUserListApi } from '@/api/fa/user'
// import { adminFaVaccineInjectOrderSeeApi } from '@/api/fa/vaccineInject'

import { zcPastureListAdminApi } from '@/api/fa/pasture'
import { sysDictRelsApi } from '@/api/dict'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import EarconRefer from './EarconRefer.vue'

import { ucDeptListApi } from '@/api/uc/dept'
import { zcVaccineDrugDetailedListApi, zcVaccineSeeApi } from '@/api/cy/VaccineInject'
import { useIcon } from '@/hooks/web/useIcon'
import { ElMessage } from 'element-plus'
const { wsCache } = useCache()

/****************************** 变量 start ******************************/
const data = ref<any>({})
const dict: any = wsCache.get('dict')
const dictRelsData = ref() // 联动数据
const breedSubData = ref([]) // 品种的枚举
const iconAdd = useIcon({ icon: 'material-symbols:add' })
const iconDel = useIcon({ icon: 'material-symbols:delete-outline' })

const fileRef = ref()

// const d_id = ref(0) //主要用来给每个行添加一个序号，删除的时候好定位

const rules = reactive({
  pasture_org_id: [required],
  pasture_dept_name: [required],
  money: [required],
  vaccine_name: [required],
  inject_date: [required]
})

/****************************** 变量 end ******************************/

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  id: {
    type: String,
    default: null
  }
})
/****************************** 组件参数 end ******************************/

// 调用查看接口获取信息
const getMedicalOrderSee = async () => {
  if (props.id) {
    const res = await zcVaccineSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = await res.data
      // 明细信息处理一下，加上d_id
      await methods.setValues(data.value)
      console.log(data.value, 'data.value')
      const Yao = await zcVaccineDrugDetailedListApi({ vaccine_order_id: props.id })
      if (Yao) {
        data.value.detailedData = await Yao.data
        console.log(Yao)
      }
    }
  } else {
    data.value.state = '1'
    data.value.detailedData = []
    data.value.fileData = []
    await methods.setValues(data.value)
  }
}

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
const onCustomer = async (value) => {
  data.value.detailedData = [] // 删除明细的数据
  data.value.pasture_dept_id = ''
  data.value.pasture_dept_name = ''
  DeptList(value)
  await methods.setValues(data.value)
}

let newTreeData = ref<any[]>([])

const DeptList = async (val) => {
  const res = await ucDeptListApi({ org_id: val })
    .catch(() => {})
    .finally(() => {
      // setTimeout(() => {
      //   loadingMain.close()
      // }, 500)
    })
  if (res) {
    newTreeData.value = res.data
    console.log(res.data, 'res')
  }
}
const schema: any = [
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListAdminApi,
      response: { count: 'count', data: 'data' },
      title: '选择创建人（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [
        { field: 'org_name', label: '牧场名称', search: { show: true } }
        // { field: 'org_id', label: '牧场编码', search: { show: true } }
      ],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer,
      disabled: props.id ? true : false
    },
    colProps: {
      span: 12
    }
  },
  {
    field: 'pasture_dept_name',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      nameField: 'pasture_dept_name',
      data: newTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      disabled: props.id ? true : false
    }
  },
  // {
  //   field: 'money',
  //   label: '费用',
  //   component: 'Input',
  //   colProps: {
  //     span: 12
  //   }
  // },
  // {
  //   field: 'vaccine_name',
  //   label: '疫苗名称',
  //   component: 'Input',
  //   colProps: {
  //     span: 12
  //   },
  //   componentProps: {
  //     disabled: props.id ? true : false
  //   }
  // },
  {
    component: 'DatePicker',
    field: 'inject_date',
    label: '注射日期',
    componentProps: {
      valueFormat: 'YYYY-MM-DD'
    },
    colProps: {
      span: 12
    }
  },
  {
    field: 'note',
    label: '备注',
    component: 'Input',
    colProps: {
      span: 12
    }
  }
  // {
  //   field: 'creation_user_id',
  //   label: '创建人',
  //   component: 'DialogRefer',
  //   componentProps: {
  //     getListApi: adminFaUserListApi,
  //     response: { count: 'count', data: 'data' },
  //     title: '选择创建人（双击选择）',
  //     nameField: 'creation_user_name',
  //     relNameField: 'nickname',
  //     valueField: 'id',
  //     crudSchemas: [
  //       { field: 'nickname', label: '姓名', search: { show: true } },
  //       { field: 'username', label: '用户名', search: { show: true } },
  //       { field: 'source', label: '类型' }
  //     ],
  //     modelName: data.value.creation_user_name
  //   }
  // }
]
const { register, methods, elFormRef } = useForm({
  schema: schema
})

const getFormData = async () => {
  let formData = await methods.getFormData()
  // const sku = unref(skuRef)
  // let skuData = sku?.getData()
  const file = unref(fileRef) //附件
  let fileData = file?.getData()
  // const goodsDetails = unref(goodsDetailsRef) //明细
  // let goods_details = goodsDetails?.getData()
  // let goods_tag = getGoodsTag()
  // let goods_details = data.value.goods_details
  // let goods_carousel = data.value.goods_carousel
  return { ...formData, fileData: fileData, detailedData: data.value.detailedData }
}

const actionType = ref('')
const d_id = ref(0)
const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'add_d':
      d_id.value++
      data.value.detailedData.push({ d_id: d_id.value })
      // await methodsForm.setValues(data.value)
      break
    case 'del_d':
      // let row_i = data.value.detailedData.findIndex((item) => {
      //   return item.d_id == row.d_id
      // })
      data.value.detailedData.splice(row.$index, 1)
      // console.log(row, 'row')

      break
    default:
      console.log('未知类型')
  }
}

const y_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  // {
  //   field: 'd_id',
  //   label: 'd_id',
  //   width: 150
  // },
  {
    field: 'type',
    label: '状态',
    width: 180
  },
  {
    field: 'drug_id',
    label: '药品名称(选择)',
    width: 170
  },
  {
    field: 'medication_name',
    label: '药品名称(手填)',
    width: 150
  },
  {
    field: 'amount',
    label: '金额',
    width: 180
  },
  {
    field: 'medication_number',
    label: '数量',
    width: 180
  },
  {
    field: 'note',
    label: '备注',
    width: 150
  },
  // {
  //   field: 'creation_time',
  //   label: '创建时间',
  //   width: 180
  // },
  {
    field: 'action',
    width: 120,
    fixed: 'right',
    label: '操作'
  }
])

defineExpose({
  elFormRef,
  getFormData
})

const www = (w) => {
  if (w.type == '1') {
    w.medication_name = null
    // console.log(w, data.value, '1')
  } else if (w.type == '2') {
    w.drug_id = null
    // console.log(w, data.value, '2')
  }
}

// const userInfo: any = wsCache.get('userInfo')

const spDrugList = async (new_data) => {
  let formData: any = await methods.getFormData()

  // console.log(new_data, userInfo, formData, 'rrr')
  if (!!formData.pasture_org_id) {
    const res = await spDrugListApi({ ...new_data, pasture_org_id: formData.pasture_org_id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      return res
    }
  } else {
    ElMessage({
      message: '请选择牧场',
      type: 'warning'
    })
    return { code: 500, count: 0, msg: '不能没有customer_id' }
  }
}
/****************************** 初始化 start ******************************/
const init = async () => {
  // 获取关联关系
  await getDictRels()
  // 调用查看接口查询数据
  await getMedicalOrderSee()
  // 跟新畜别
  if (data.value.breed) {
    await breedGetSub(data.value.breed)
  }
}
init()

const row_num = ref()
const du = (row) => {
  // row_num.value = row.d_id - 1
  console.log(row, '77')
  row_num.value = row
}
const drug = (a, b) => {
  // console.log(data.value.detailedData, row_num.value)
  // data.value.detailedData[row_num.value].medication_name = b
  console.log(a, b, '666')
  row_num.value.medication_name = a
  console.log(data.value.detailedData, '888')
}

/****************************** 初始化 end ******************************/
</script>
<template>
  <div>
    <ContentWrap title="主数据">
      <Form :rules="rules" @register="register" :data="data || {}" />
    </ContentWrap>
    <!-- <ContentWrap title="附件">
      <UploadMultiple
        ref="fileRef"
        v-model="data.fileData"
        :response="{
          url: 'file_url',
          name: 'file_name',
          file_type: 'file_type'
        }"
      />
    </ContentWrap> -->
    <ContentWrap title="药品明细数据">
      <div class="mb-10px">
        <!-- <ElButton type="primary">新增行</ElButton> -->
        <ElButton circle :icon="iconAdd" @click="action('add_d')" title="新增行" />
      </div>
      <!-- <template #default="scope"> -->
      <Table :columns="y_columns" :data="data.detailedData" :selection="false" :border="true">
        <!-- <template #default="scope"> -->
        <template #drug_id="{ row }">
          <EarconRefer
            v-model="row.drug_id"
            :getListApi="spDrugList"
            :response="{ count: 'count', data: 'data' }"
            title="选择药品（双击选择）"
            nameField="id"
            relNameField="name"
            valueField="id"
            :crudSchemas="[
              // { field: 'is_selected', label: '是否已选', search: { show: false }, width: 120 },
              { field: 'id', label: '药品ID', search: { show: false } },
              { field: 'available_stock', label: '药品可用库存', search: { show: false } },
              { field: 'name', label: '药品名称', search: { show: true } },
              { field: 'note', label: '药品备注', search: { show: false } }
            ]"
            :modelName="row.drug_name"
            :selected="data.detailedData"
            @change="drug"
            @click="du(row)"
            v-if="row.type == 1"
          />
        </template>
        <!-- </template> -->
        <template #medication_name="{ row }">
          <ElInput v-model="row.medication_name" v-if="row.type == 2" />
          <span></span>
        </template>

        <template #amount="{ row }">
          <ElInput v-model="row.amount" v-if="row.type == 2" />
        </template>

        <template #medication_number="{ row }">
          <ElInput v-model="row.medication_number" />
        </template>

        <template #note="{ row }">
          <ElInput v-model="row.note" />
        </template>

        <template #type2="scope">
          <ElSelectV2 v-model="scope.row.type" :options="dict.medical_drug_type" />
        </template>
        <template #type="scope">
          <el-select
            @change="www(scope.row)"
            v-model="scope.row.type"
            class="m-2"
            placeholder="请选择"
          >
            <el-option
              v-for="item in dict.medical_drug_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
        <template #creation_time="{ row }">
          <ElDatePicker v-model="row.creation_time" style="width: 150px" valueFormat="YYYY-MM-DD" />
        </template>

        <template #action="row">
          <!-- <ElButton circle :icon="iconFile" @click="action('file_d', row)" title="附件" /> -->
          <!-- <template #default="scope"> -->
          <ElButton circle :icon="iconDel" @click="action('del_d', row)" title="删除行" />
          <!-- </template> -->
        </template>
      </Table>
      <!-- </template> -->
    </ContentWrap>
  </div>
</template>
